// app/model/product_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DECIMAL, TEXT, ENUM, DATE } = app.Sequelize;

  const Product = app.model.define('product', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    organizationId: {
      type: INTEGER,
      allowNull: false,
      field: 'organization_id',
      comment: '组织ID'
    },
    sku: {
      type: STRING(100),
      allowNull: false,
      unique: true,
      comment: '产品SKU'
    },
    name: {
      type: STRING(200),
      allowNull: false,
      comment: '产品名称'
    },
    specification: {
      type: STRING(500),
      comment: '产品规格'
    },
    unit: {
      type: STRING(50),
      comment: '单位'
    },
    categoryId: {
      type: INTEGER,
      allowNull: true,
      field: 'category_id',
      comment: '产品类目ID'
    },
    brandId: {
      type: INTEGER,
      allowNull: true,
      field: 'brand_id',
      comment: '品牌ID'
    },
    description: {
      type: TEXT,
      comment: '产品描述'
    },
    stock: {
      type: INTEGER,
      defaultValue: 0,
      comment: '当前库存'
    },
    minStock: {
      type: INTEGER,
      defaultValue: 0,
      field: 'min_stock',
      comment: '安全库存'
    },
    salePrice: {
      type: DECIMAL(10, 2),
      defaultValue: 0,
      field: 'sale_price',
      comment: '售价'
    },
    costPrice: {
      type: DECIMAL(10, 2),
      defaultValue: 0,
      field: 'cost_price',
      comment: '成本价'
    },
    status: {
      type: ENUM('active', 'inactive', 'outofstock'),
      defaultValue: 'active',
      comment: '产品状态: active-在售, inactive-下架, outofstock-缺货'
    },
    createdAt: {
      type: DATE,
      field: 'created_at'
    },
    updatedAt: {
      type: DATE,
      field: 'updated_at'
    }
  }, {
    tableName: 'products',
    timestamps: true,
    underscored: true // 使用下划线命名
  });

  // 添加关联关系
  Product.associate = function() {
    // 产品与组织的关联
    if (app.model.OrganizationModel) {
      Product.belongsTo(app.model.OrganizationModel, {
        foreignKey: 'organizationId',
        as: 'organization'
      });
    }

    // 产品与类目的关联
    if (app.model.ProductCategoryModel) {
      Product.belongsTo(app.model.ProductCategoryModel, {
        foreignKey: 'categoryId',
        as: 'category'
      });
    }

    // 产品与品牌的关联
    if (app.model.BrandModel) {
      Product.belongsTo(app.model.BrandModel, {
        foreignKey: 'brandId',
        as: 'brand'
      });
    }
  };

  return Product;
};